import { onMounted, reactive, watch } from 'vue'

export function useAuth(){

    const user = reactive({
        isLogin:false,
        token:null,
        username:''
    })

    // 登录
    const login=(token,username)=>{
        // 赋值
        user.token=token
        user.username=username
        user.isLogin = true
    }

    // 登出
    const logout = ()=>{
        user.isLogin=false
        user.token=null
        user.username=''
    }

    // 验证token
    const authStatus=async()=>{
        // 从localStorage中获取token
        const savedToken=localStorage.getItem('authToken')
        if(savedToken){
            // 模拟调用
            setTimeout(() => {
                if(savedToken === 'val-token'){
                    login(savedToken,'授权用户')
                }else{
                    logout()
                }
            }, 300);
        }else{
            logout()
        }
    }
    
    onMounted(authStatus)
    
    watch(()=>user.token,(newToken)=>{
        if(!newToken){
            logout()
            localStorage.removeItem('authToken')
        }else{
            localStorage.setItem('authToken',newToken)
        }
    })

    return {
        user,
        login,
        logout
    }

}